package org.xxpay.pay.channel.siji;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Service;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.HtmlUtils;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.common.util.str.StringUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.DateUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;

import java.util.Map;
import java.util.Random;

@Service
public class SijiPaymentService extends BasePayment {

    private final static String logPrefix = "【四季支付支付】";
    @Override
    public String getChannelName() {
        return SijiConfig.CHANNEL_NAME;
    }

    /**
     * 支付下单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject pay(PayOrder payOrder){
        return doOrderReq(payOrder);
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject query(PayOrder payOrder){
        JSONObject retObj = buildRetObj();
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "没有订单查询接口");
        return retObj;
    }

    //下单具体实现
    private JSONObject doOrderReq(PayOrder payOrder){
        SijiConfig config = new SijiConfig(getPayParam(payOrder));
        Map<String,Object> params = Maps.newHashMap();
        //设置请求参数
        setParams(payOrder, config, params);
        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(params));
        //将订单改为支付中
        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
        String reslut=null;
        try {
            reslut = HtmlUtils.sendHttpPost(config.getRequestUrl()+SijiConfig.REQ_PAY_URL_FIXX,JSON.toJSONString(params));
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject origin = JSONObject.parseObject(reslut);
        _log.info("{}响应数据:{}", getChannelName(), JSON.toJSONString(origin));
        // 响应对象
        JSONObject retObj = new JSONObject();
        if(StringUtils.equals("0",origin.getString("error"))){
            JSONObject data = origin.getJSONObject("data");
            return  buildPayResultOfForm(retObj, payOrder,"<script type=\"text/javascript\">\n" +
                        "　　window.location.href=\""+ data.getString("payurl")+"\";\n" +
                        "　　</script>" );

        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.toJSONString());
        return retObj;
   
    } 

    //设置请求参数
    private void setParams(PayOrder payOrder, SijiConfig config,Map<String,Object> params){

        params.put("mchid", config.getAppId());
        params.put("timestamp", DateUtil.getSeqString());
        params.put("nonce", getRandomString(10));
        params.put("data", getData(payOrder, config));
        params.put("sign", getSign(params, config.getPrivateKey()));
    }
    private JSONObject getData(PayOrder payOrder, SijiConfig config){
        JSONObject data = new JSONObject();
        data.put("paytype", config.getPayMode());
        data.put("out_trade_no", payOrder.getPayOrderId());
        data.put("goodsname", payOrder.getPayOrderId());
        data.put("total_fee", AmountUtil.convertCent2Dollar(String.valueOf(payOrder.getAmount())));
        data.put("notify_url", payConfig.getNotifyUrl(getChannelName()));
        data.put("return_url", payOrder.getReturnUrl());
        data.put("requestip", payOrder.getClientIp());
        return data;
    }
    //获取sign
    private String getSign(Map<String,Object> params,String key){
        String signTxt = SignUtils.parameterText(params);
        _log.info("{}待签名字符串：{}", logPrefix, signTxt+"&key"+key);
        String sign = SignUtils.MD5.createSign(signTxt, "&key"+key, SignUtils.CHARSET_UTF8);
        return sign;
    }

    /**
     * 获取随机字符串
     * @param length
     * @return
     */
    private static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
}

